/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"fmt"
	"github.com/BurntSushi/xgb/xproto"
	"github.com/BurntSushi/xgbutil"
	"github.com/BurntSushi/xgbutil/ewmh"
	"github.com/BurntSushi/xgbutil/xwindow"
)

var _X *xgbutil.XUtil

func getWindowName(X *xgbutil.XUtil, xid uint32) (name string) {
	var err error

	if name, err = ewmh.WmNameGet(X, xproto.Window(xid)); err != nil {
		fmt.Printf("Get '%v' window name failed: %v\n", xid, err)
		return
	}

	return
}

func getWindowParentXid(X *xgbutil.XUtil, xid uint32) (pXid uint32) {
	win := xwindow.New(X, xproto.Window(xid))

	if parentXid, err := win.Parent(); err != nil {
		fmt.Printf("Get '%v' parent xid failed: %v\n", xid, err)
	} else {
		pXid = uint32(parentXid.Id)
	}

	return
}

func getXUtil() *xgbutil.XUtil {
	if _X == nil {
		X, err := xgbutil.NewConn()
		if err != nil {
			fmt.Println("New XUtil Failed:", err)
			return nil
		}

		_X = X
	}

	return _X
}

func main() {
	X := getXUtil()
	if X == nil {
		return
	}

	name := getWindowName(X, 65011728)
	fmt.Printf("xid: 65011728 window name: %v\n", name)

	pXid := getWindowParentXid(X, 65011728)
	fmt.Printf("xid: 65011728 parent xid: %v\n", pXid)

	name = getWindowName(X, pXid)
	fmt.Printf("xid: %v window name: %v\n", pXid, name)
}
